package com.h4313.ghome.ui;

import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.h4313.ghome.GHomeApplication;
import com.h4313.ghome.R;
import com.h4313.ghome.io.NetworkHelper;

public class LoginActivity extends Activity implements OnClickListener {

	EditText mIp, mLogin, mPassword;
	Button mLoginBtn;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		
		setContentView(R.layout.activity_login);
		
		mIp = (EditText) findViewById(R.id.login_ip);
		mLogin = (EditText) findViewById(R.id.login_login);
		mPassword = (EditText) findViewById(R.id.login_password);
		mLoginBtn = (Button) findViewById(R.id.login_connect);
		mLoginBtn.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.login_connect) {
			
			new AsyncTask<Void, Void, Boolean>() {

				@Override
				protected void onPreExecute() {
					setProgressBarIndeterminateVisibility(true);
					
					GHomeApplication.SERVER_URL = mIp.getText().toString();
					
					String encoded = mLogin.getText().toString()+":"+mPassword.getText().toString();
					GHomeApplication.SERVER_AUTH = Base64.encodeToString(encoded.getBytes(), Base64.DEFAULT);
				}
				
				@Override
				protected Boolean doInBackground(Void... params) {
					
					try {
						NetworkHelper.downloadUrl(GHomeApplication.SERVER_URL + "/modules", 10000, 10000);
						return true;
					} catch (IOException e) {
						e.printStackTrace();
					}
					return false;
				}
				
				protected void onPostExecute(Boolean result) {
					
					setProgressBarIndeterminateVisibility(false);
					
					if (result) {
						Intent i = new Intent(LoginActivity.this, HomeActivity.class);
						startActivity(i);
						finish();
					} else {
						Toast.makeText(LoginActivity.this, "Impossible de se connecter au serveur", Toast.LENGTH_SHORT).show();
					}
				};
				
			}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
			
		}
	}
	
	
	
}
